<?php

namespace App\Module\User\Service;

use App\Constants\Constant;
use App\Model\Agree;
use App\Model\Works;
use Hyperf\Di\Annotation\Inject;
use Qbhy\HyperfAuth\AuthManager;

class WorksService{

    /**
     * @Inject()
     * @var AuthManager $authManager
     */
    private $authManager;

    public function search($pagesize){
        return Works::query()->withCount("agrees as agrees")->latest("works_id")->paginate($pagesize);
    }

    public function getById($id)
    {
        $model = Works::query()->withCount("agrees")->find($id);
        if($this->authManager->guard(Constant::USER)->guest()){
            $already_agree = false;
        }else{
            $already_agree = $model->agrees()->where("user_id",$this->authManager->guard(Constant::USER)->user()->getId())->exists();
        }
        $model->setAttribute("already_agree",$already_agree);
        return $model;
    }

    public function agree($id){
        $query = Agree::query()->where([['source_id',$id],['user_id',$this->authManager->guard(Constant::USER)->user()->getId()],['origin',Constant::ORIGIN_WORKS]]);
        if($query->exists()){
            return $query->delete();
        }
        $model = new Agree();
        $model->setAttribute("source_id",$id);
        $model->setAttribute("user_id",$this->authManager->guard(Constant::USER)->user()->getId());
        $model->setAttribute("origin",Constant::ORIGIN_WORKS);
        return $model->save();
    }
}